package cn.virens.web.components.weixin.config;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;

public abstract class WxMpAbstractCacheConfigStorage extends WxMpInMemoryConfigStorage {
	private String prefix = "weixn:";
	private String jsapiTicketKey = ":jsapi_ticket";
	private String accessTokenKey = ":access_token";
	private String cardapiTicketKey = ":cardapi_ticket";

	@Override
	public String getAccessToken() {
		return get(key(accessTokenKey));
	}

	@Override
	public boolean isAccessTokenExpired() {
		return has(key(accessTokenKey));
	}

	@Override
	public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
		this.put(key(accessTokenKey), accessToken, expiresInSeconds);
	}

	@Override
	public void expireAccessToken() {
		this.put(key(accessTokenKey), null, 0);
	}

	@Override
	public String getJsapiTicket() {
		return get(key(jsapiTicketKey));
	}

	@Override
	public boolean isJsapiTicketExpired() {
		return has(key(jsapiTicketKey));
	}

	@Override
	public synchronized void updateJsapiTicket(String jsapiTicket, int expiresInSeconds) {
		this.put(key(jsapiTicketKey), jsapiTicket, expiresInSeconds);
	}

	@Override
	public void expireJsapiTicket() {
		this.put(key(jsapiTicketKey), null, 0);
	}

	@Override
	public String getCardApiTicket() {
		return get(key(cardapiTicketKey));
	}

	@Override
	public boolean isCardApiTicketExpired() {
		return has(key(cardapiTicketKey));
	}

	@Override
	public synchronized void updateCardApiTicket(String cardApiTicket, int expiresInSeconds) {
		this.put(key(cardapiTicketKey), cardApiTicket, expiresInSeconds);
	}

	@Override
	public void expireCardApiTicket() {
		this.put(key(cardapiTicketKey), null, 0);
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getAccessTokenKey() {
		return accessTokenKey;
	}

	public void setAccessTokenKey(String accessTokenKey) {
		this.accessTokenKey = accessTokenKey;
	}

	public String getJsapiTicketKey() {
		return jsapiTicketKey;
	}

	public void setJsapiTicketKey(String jsapiTicketKey) {
		this.jsapiTicketKey = jsapiTicketKey;
	}

	public String getCardapiTicketKey() {
		return cardapiTicketKey;
	}

	public void setCardapiTicketKey(String cardapiTicketKey) {
		this.cardapiTicketKey = cardapiTicketKey;
	}

	protected final String key(String key) {
		return prefix + appId + key;
	}

	protected abstract String get(String key);

	protected abstract boolean has(String key);

	protected abstract void put(String key, String value, long timeout);
}
